package com.shishuo.cms.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shishuo.cms.dao.OrderDao;
import com.shishuo.cms.dao.OrderDetailDao;
import com.shishuo.cms.entity.Order;
import com.shishuo.cms.entity.OrderDetail;
import com.shishuo.cms.entity.User;
import com.shishuo.cms.entity.vo.PageVo;

/**
 * 订单
 * 
 * @author magang
 *
 */
@Service
public class OrderService {
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderDetailDao orderDetailDao;
	@Autowired
	private ProductService productService;
	/**
	 * 添加订单
	 * 
	 * @param Order
	 * @return Integer
	 * 
	 */
	public void insert(Order order){
		orderDao.insert(order);
		for (OrderDetail orderDetail : order.getOrderDetails()) {
			orderDetail.setOrderId(order.getId());
			orderDetailDao.insert(orderDetail);
		}
	}

	public int update(Order order){
		return orderDao.update(order);
	}

	/**
	 * 删除订单
	 * 
	 * @param OrderId
	 * @return Integer
	 * 
	 */
	public int deleteOrder(int id){
		return orderDao.deleteOrder(id);
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public Order selectById(int id){
		return orderDao.selectById(id);
	}

	/**
	 * 获取所有订单
	 * 
	 * @param offset
	 * @param rows
	 * @return List<Order>
	 * 
	 */
	public PageVo<Order> getAllList(Map<String, Object> map,
			int offset){
		PageVo<Order> pageVo = new PageVo<Order>(offset);
		pageVo.setRows(Integer.MAX_VALUE);
		map.put("offset", pageVo.getOffset());
		map.put("rows", pageVo.getRows());
		List<Order> list=orderDao.getAllList(map);
		for (Order order : list) {
			List<OrderDetail> orderDetails=orderDetailDao.getAllListByOrderId(order.getId());
			for (OrderDetail orderDetail : orderDetails) {
				orderDetail.setProduct(productService.getProductById(orderDetail.getProductId()));
			}
			order.setOrderDetails(orderDetails);
		}
		pageVo.setList(list);
		pageVo.setCount(this.getAllListCount());
		return pageVo;
	}
	
	public int getAllListCount() {
		return orderDao.getAllListCount();
	}
}
